package com.copa.l2363;

import java.util.*;

/**
 * @author copa
 * @createDate 2023-02-28 11:20
 * @function 哈希表+排序法
 */
public class Test1 {

    public List<List<Integer>> mergeSimilarItems(int[][] items1, int[][] items2) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int i = 0;
        int minN = items1.length > items2.length ? items2.length : items1.length;
        int maxN = items1.length > items2.length ? items1.length : items2.length;
        for (; i < minN; i++) {
            map.put(items1[i][0], map.getOrDefault(items1[i][0], 0) + items1[i][1]);
            map.put(items2[i][0], map.getOrDefault(items2[i][0], 0) + items2[i][1]);
        }
        boolean flag = items1.length > items2.length;
        for (; i < maxN; i++) {
            if (flag) {
                map.put(items1[i][0], map.getOrDefault(items1[i][0], 0) + items1[i][1]);
                continue;
            }
            map.put(items2[i][0], map.getOrDefault(items2[i][0], 0) + items2[i][1]);
        }
        List<List<Integer>> result = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            List<Integer> temp = new ArrayList<>();
            temp.add(entry.getKey());
            temp.add(entry.getValue());
            result.add(temp);
        }
        result.sort((l1, l2) -> l1.get(0) > l2.get(0) ? 1 : -1);
        return result;
    }

    public static void main(String[] args) {
        //int[][] items1 = {{1,1},{4,5},{3,8}};
        //int[][] items2 = {{3,1},{1,5}};
        int[][] items1 = {{15,5},{2,6},{5,3},{14,8},{12,4},{19,6},{25,4},{13,4},{9,1}};
        int[][] items2 = {{15,9},{2,4},{5,2},{14,4},{12,3},{19,10},{25,7},{13,6},{9,9}};
        List<List<Integer>> result = new Test1().mergeSimilarItems(items1, items2);
        for (List<Integer> list : result) {
            System.out.println(list.get(0) + ":" + list.get(1));
        }
    }
}
